//
//  RecommendViewController.m
//  QYer
//
//  Created by lanou on 16/8/5.
//  Copyright © 2016年 CaiZhuYu. All rights reserved.
//

#import "RecommendViewController.h"
#import "RecommendCarouselModel.h"
#import "CarouselDetailViewController.h"

#import "RecommendNextStationModel.h"
#import "RecommendSpecialDiscountModel.h"

#import "RecommendNextStationCell.h"
#import "RecommendSpecialDiscountCell.h"
#import "RecommendPopularTravelCell.h"

#import "KitsViewController.h"
#import "BookHotelViewController.h"
#import "DiscountViewController.h"
#import "JourneyViewController.h"
#import "SearchViewController.h"

#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height
@interface RecommendViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

//轮播图数组
@property (nonatomic, strong) NSMutableArray *carouselArray;

@property (nonatomic, strong) UITableView *tableView;
//发现下一站的数组
@property (nonatomic, strong) NSMutableArray *nextStationArray;
//抢特价折扣的数组
@property (nonatomic, strong) NSMutableArray *specialDiscountArray;
//热门游记数组
@property (nonatomic, strong) NSMutableArray *popularTravelArray;

@property (nonatomic, assign) NSInteger page;

@end

@implementation RecommendViewController

- (NSMutableArray *)carouselArray {
    if (!_carouselArray) {
        _carouselArray = [NSMutableArray array];
    }
    return _carouselArray;
}

- (NSMutableArray *)nextStationArray {
    if (!_nextStationArray) {
        _nextStationArray = [NSMutableArray array];
    }
    return _nextStationArray;
}

- (NSMutableArray *)specialDiscountArray {
    if (!_specialDiscountArray) {
        _specialDiscountArray = [NSMutableArray array];
    }
    return _specialDiscountArray;
}

- (NSMutableArray *)popularTravelArray {
    if (!_popularTravelArray) {
        _popularTravelArray = [NSMutableArray array];
    }
    return _popularTravelArray;
}


#pragma mark ----- ViewsAndData -----

- (void)requestData {
    
    [NetWorkTool requstWithType:GET URLString:kRecommendUrl parameter:nil callBack:^(NSData *data, NSError *error) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        //轮播图
        for (NSDictionary *dic in jsonDic[@"data"][@"slide"]) {
            RecommendCarouselModel *model = [[RecommendCarouselModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.carouselArray addObject:model];
        }
        //NSLog(@"推荐页轮播图:%@", self.carouselArray);
        
        //下一站
        for (NSDictionary *dic in jsonDic[@"data"][@"subject"]) {
            RecommendNextStationModel *model = [[RecommendNextStationModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.nextStationArray addObject:model];
        }
        //NSLog(@"下一站:%@", self.nextStationArray);
        
        //特价折扣
        // 头 jsonDic[@"data"][@"discount_subject"];
        for (NSDictionary *dic in jsonDic[@"data"][@"discount"]) {
            RecommendSpecialDiscountModel *model = [[RecommendSpecialDiscountModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.specialDiscountArray addObject:model];
        }
        //NSLog(@"特价:%@", self.specialDiscountArray);
        //RecommendSpecialDiscountModel *model = self.specialDiscountArray.firstObject;
        //NSLog(@"特价: %@", model.price);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 350)];
            NSMutableArray *photoArray = [NSMutableArray array];
            for (NSInteger i = 0; i < self.carouselArray.count; i++) {
                RecommendCarouselModel *model = self.carouselArray[i];
                [photoArray addObject:model.photo];
            }
            CarouselView *carousel = [[CarouselView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200) imageUrls:photoArray];
            //[self.view addSubview:carousel];
            [headerView addSubview:carousel];
            
            //轮播图点击事件
            carousel.imageClickBlock = ^(NSInteger index){
                RecommendCarouselModel *model = self.carouselArray[index];
                //NSLog(@"推荐页第%ld张轮播图:%@", index, model.url);
                CarouselDetailViewController *carouselDetailVC = [[CarouselDetailViewController alloc] init];
                carouselDetailVC.urlString = model.url;
                [self.navigationController pushViewController:carouselDetailVC animated:YES];
            };
            
            
            //4个按钮部分
            NSArray *titles = @[@"看锦囊", @"抢折扣", @"订酒店", @"旅途中"];
            CGFloat buttonW = (kWidth-80) / 4;
            CGFloat buttonH = buttonW + 30;
            for (int i = 0; i < titles.count; i++) {
                CustomButton *button = [[CustomButton alloc] init];
                button.tag = 100 + i;
                button.frame = CGRectMake(i*(buttonW+20)+10, 220, buttonW, buttonH);
                [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
                [button setTitle:titles[i] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:titles[i]] forState:UIControlStateNormal];
                //[self.view addSubview:button];
                [headerView addSubview:button];
            }
            
            self.tableView.tableHeaderView = headerView;
            [self.tableView reloadData];
        });
        
        
    }];
}

- (void)createSubViews {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendNextStationCell" bundle:nil] forCellReuseIdentifier:@"NextStationReuse"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendSpecialDiscountCell" bundle:nil] forCellReuseIdentifier:@"SpecialDiscountReuse"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendPopularTravelCell" bundle:nil] forCellReuseIdentifier:@"PopularTravelReuse"];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.popularTravelArray removeAllObjects];
        [self requestPopularTravelData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self requestPopularTravelData];
    }];
}

//热门游记
- (void)requestPopularTravelData {
    NSString *urlOne = @"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&oauth_token=81f78185dee6dc6040e10b8c43ad4b19&page=";
    NSString *urlTwo = @"&track_app_channel=App%2520Store&track_app_version=6.9.4&track_device_info=iPhone%25205%28ChinaMobile%2CChinaTelecom%2CChinaUnicom%29&track_deviceid=2D9E8D6C-2140-49DC-993D-D66133CC22C0&track_os=ios%25209.3.2&track_user_id=8252405&type=index&v=1";
    NSString *url = [NSString stringWithFormat:@"%@%ld%@", urlOne, _page, urlTwo];
    //NSLog(@"热门游记网址: %@", url);
    
    [NetWorkTool requstWithType:GET URLString:url parameter:@{@"page":@(_page)} callBack:^(NSData *data, NSError *error) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dic in jsonDic[@"data"]) {
            RecommendPopularTravelModel *model = [[RecommendPopularTravelModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.popularTravelArray addObject:model];
        }
        //NSLog(@"热门游记:%@", self.popularTravelArray);
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        });
    }];
}

//上拉下拉
- (void)headerAndFooter {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 0;
        [self requestPopularTravelData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page += 1;
        
        [self requestPopularTravelData];
    }];
}


#pragma mark ----- ViewController -----

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.view.backgroundColor = [UIColor cyanColor];
    
    [self requestData];
    
    [self createSubViews];
    
    
    //[self requestPopularTravelData];
    [self headerAndFooter];
    
    
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    self.navigationItem.titleView = searchBar;
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)buttonClick:(UIButton *)button {
    if (button.tag == 100) {
        NSLog(@"看锦囊!");
        KitsViewController *kitsVC = [[KitsViewController alloc] init];
        [self.navigationController pushViewController:kitsVC animated:YES];
    } else if (button.tag == 101) {
        NSLog(@"抢折扣!");
        DiscountViewController *discountVC = [[DiscountViewController alloc] init];
        [self.navigationController pushViewController:discountVC animated:YES];
    } else if (button.tag == 102) {
        NSLog(@"订酒店!");
        BookHotelViewController *bookHotelVC = [[BookHotelViewController alloc] init];
        [self.navigationController pushViewController:bookHotelVC animated:YES];
    } else if (button.tag == 103) {
        NSLog(@"旅途中!");
        JourneyViewController *journeyVC = [[JourneyViewController alloc] init];
        [self.navigationController pushViewController:journeyVC animated:YES];
    }
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark ----- UITableViewDelegate -----

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return self.nextStationArray.count;
            break;
        case 2:
            return self.specialDiscountArray.count;
            break;
        default:
            return self.popularTravelArray.count;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
        }
        cell.textLabel.text = @"点评我去过的目的地,帮助更多穷游er";
        return cell;
    } else if (indexPath.section == 1) {
        RecommendNextStationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NextStationReuse" forIndexPath:indexPath];
        RecommendNextStationModel *model = self.nextStationArray[indexPath.row];
        [cell.photoView sd_setImageWithURL:[NSURL URLWithString:model.photo] placeholderImage:[UIImage imageNamed:@"占位图"]];
                return cell;
    } else if (indexPath.section == 2) {
        RecommendSpecialDiscountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SpecialDiscountReuse" forIndexPath:indexPath];
        RecommendSpecialDiscountModel *model = self.specialDiscountArray[indexPath.row];
        [cell setContentWithModel:model];
        return cell;
    } else {
        RecommendPopularTravelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PopularTravelReuse" forIndexPath:indexPath];
        [cell setContentsWithModel:self.popularTravelArray[indexPath.row]];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return 50;
            break;
        case 1:
            return 200;
            break;
        case 2:
            return 300;
            break;
        default:
            return 150;
            break;
    }
}

//区头
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *titleArray = @[@"发现下一站", @"抢特价折扣", @"看热门游记"];
    if (section == 0) {
        return nil;
    } else {
        return titleArray[section-1];
    }
}

//点击Cell的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //NSLog(@"第%ld区,第%ld行", indexPath.section, indexPath.row);
    
    if (indexPath.section == 0) {
        //确认是否登陆
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"username"]) {
            //已经登录状态
            NSLog(@"已经登录过!");
        } else {
            UINavigationController *naVC = [[UIStoryboard storyboardWithName:@"LoginAndRegist" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginAndRegist"];
            [self presentViewController:naVC animated:YES completion:nil];
        }
        
        
    } else if (indexPath.section == 1) {
        //下一站
        DetailViewController *detailVC = [[DetailViewController alloc] init];
        RecommendNextStationModel *model = self.nextStationArray[indexPath.row];
        detailVC.urlString = model.url;
        [self.navigationController pushViewController:detailVC animated:YES];
    } else if (indexPath.section == 2) {
        //特价折扣
    } else {
        //热门游记
        DetailViewController *detailVC = [[DetailViewController alloc] init];
        RecommendPopularTravelModel *model = self.popularTravelArray[indexPath.row];
        detailVC.urlString = model.view_author_url;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


#pragma mark ----- UISearchBarDelegate -----

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:searchVC];
    [self presentViewController:naVC animated:YES completion:nil];
}









@end
